package logic

import (
	"Junior_two/subject/usercenter/userapi/internal/svc"
	"Junior_two/subject/usercenter/userapi/internal/types"
	"Junior_two/subject/usercenter/userapi/internal/utils"
	"Junior_two/subject/usercenter/userrpc/pb/user"
	"context"
	"github.com/astaxie/beego/validation"
	_ "github.com/astaxie/beego/validation"
	"github.com/dgrijalva/jwt-go/v4"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"strconv"
	"time"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegRequest) (resp *types.RegResponse, err error) {
	// todo: add your logic here and delete this line
	userName := req.Username
	password := req.Password
	mobile := req.Mobile
	sms := req.Sms
	valid := validation.Validation{}
	valid.Required(userName, "username").Message("用户名不可以为空")
	valid.Required(password, "password").Message("密码不能为空")
	valid.Required(mobile, "mobile").Message("手机号不能为空")
	valid.Required(sms, "sms").Message("验证码不能为空")
	if valid.HasErrors() {
		for _, v := range valid.Errors {
			return &types.RegResponse{
				Msg:  v.Message,
				Code: http.StatusAccepted,
			}, nil
		}
	}
	key := "sms:code_" + mobile
	s, e := utils.GetSms(key)
	if e == false {
		return &types.RegResponse{
			Msg:  "验证码有误",
			Code: http.StatusAccepted,
		}, nil
	}
	code, _ := strconv.Atoi(s)
	intSms, _ := strconv.Atoi(sms)
	if code != intSms {
		return &types.RegResponse{
			Msg:  "验证码有误",
			Code: http.StatusAccepted,
		}, nil
	}
	res, err := l.svcCtx.UserServer.Reg(l.ctx, &user.RegRequest{
		Username: userName,
		Password: password,
		Mobile:   mobile,
	})
	if err != nil {
		return &types.RegResponse{
			Msg:  "注册失败",
			Code: http.StatusAccepted,
		}, nil
	}
	if res.Code != http.StatusOK {
		return &types.RegResponse{
			Msg:  res.Msg,
			Code: res.Code,
		}, nil
	}
	//获取用户信息
	data, err := l.svcCtx.UserServer.UserInfo(l.ctx, &user.UserRequest{Username: userName})
	if err != nil {
		return &types.RegResponse{
			Msg:  "获取用户信息失败",
			Code: http.StatusAccepted,
		}, nil
	}
	//注册成功之前进行token 认证
	utils.CreateJwt([]byte(l.svcCtx.Config.Auth.AccessSecret), &utils.MyCustomClaims{
		UserId:   data.Id,
		Username: data.Username,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: jwt.NewTime(float64(time.Now().Unix() + l.svcCtx.Config.Auth.AccessExpire)),
		},
	})
	return &types.RegResponse{
		Msg:  res.Msg,
		Code: res.Code,
	}, nil
}
